package auction.securechannel;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.security.PrivateKey;
import java.security.PublicKey;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;

import org.apache.log4j.Logger;

public class TCPChannel implements Channel{
	public static Logger log = Logger.getLogger(TCPChannel.class);

	private PublicKey publicKey;
	private PrivateKey privateKey;

	private SecretKey secretKey;
	private IvParameterSpec ivParameter;

	private Socket socket;
	private BufferedReader in;
	private PrintWriter out;

	public TCPChannel(Socket socket) throws IOException {
		this.socket=socket;
		out = new PrintWriter(this.socket.getOutputStream(), true);
		in = new BufferedReader(new InputStreamReader(this.socket
				.getInputStream()));
	}

	public void send(byte[]  message) {
		out.println(new String(message));
	}

	public byte[]  receive()  {

		String inLine = null;
		try {
			inLine = in.readLine();
		} catch (IOException e) {
			log.debug("Error: "+e.getMessage());
		}

		if((inLine!=null)){
				return inLine.getBytes();
		}			 
		else {
			return null;
		}
	}

	public PublicKey getPublicKey() {

		return publicKey;
	}
	public void setPublicKey(PublicKey publicKey) {
		this.publicKey = publicKey;
	}
	public  PrivateKey getPrivateKey() {
		return privateKey;
	}
	public  void setPrivateKey(PrivateKey privateKey) {
		this.privateKey = privateKey;
	}

	public SecretKey getSecretKey() {
		return secretKey;
	}

	public void setSecretKey(SecretKey secretKey) {
		this.secretKey = secretKey;
	}

	public IvParameterSpec getIvParameter() {
		return ivParameter;
	}

	public void setIvParameter(IvParameterSpec ivParameter) {
		this.ivParameter = ivParameter;
	}
	public void closeSocket(){
		try {
			this.socket.close();
			in.close();
			out.close();
		} catch (IOException e) {
			log.debug("Error: "+e.getMessage());
		}
	}

}
